package cn.car91.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import cn.car91.R;
import cn.car91.bean.RepairShop;
import cn.car91.http.HttpHandler;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.utils.EarthUtil;
import cn.car91.utils.EarthUtil.Location;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HerilyAlertDialog;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

public class AidActivity extends BaseActivity {

    LocationClient locationClient;
    LocationClientOption option;

    @ViewInject(R.id.aid_phone_list)
    TableLayout phoneListView;
    @ViewInject(R.id.aid_traffic_aid)
    TextView trafficView;
    @ViewInject(R.id.aid_trail_aid)
    TextView trailView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_aid);
        super.onCreate(savedInstanceState);

        for (int i = 0; i < phoneListView.getChildCount(); i++) {
            phoneListView.getChildAt(i).setOnClickListener(onPhoneClickListener);
        }

        //设置定位条件
        option = getCar91Application().getLocationOption();
        option.setScanSpan(getCar91Application().UPDATE_TIME_SHORT);    //设置定时定位的时间间隔。单位毫秒

        locationClient = getCar91Application().getmLocationClient();
        locationClient.setLocOption(option);
        locationClient.registerLocationListener(bdLocationLinstener);

        ((TextView) findViewById(R.id.header_text)).setText("紧急救援电话");
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        option.setScanSpan(getCar91Application().UPDATE_TIME_SHORT);
        locationClient.setLocOption(option);

        if (!locationClient.isStarted())
            locationClient.start();
        if (locationClient.isStarted())
            locationClient.requestOfflineLocation();

        super.onResume();
    }

    private BDLocationListener bdLocationLinstener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (location == null) {
                trafficView.setText(R.string.aid_default);
                trailView.setText(R.string.aid_default);
            } else {
                Double lat = location.getLatitude();
                Double lon = location.getLongitude();

                Location myLocation = EarthUtil.getLocationRadius(lat, lon, 50f);//50km范围内

                HttpHandler.httpHandler.getAroundRepairShop(1, lat, lon, myLocation.lat, myLocation.lon, "7",null,null, callTrafficBack);
                HttpHandler.httpHandler.getAroundRepairShop(1, lat, lon, myLocation.lat, myLocation.lon, "6",null,null, callHelpBack);
                locationClient.stop();
            }
        }

        //拖车
        RequestCallBack callTrafficBack = new RequestCallBack() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                trailView.setText(R.string.app_company_customer_phone);
            }

            @Override
            public void onSuccess(ResponseInfo arg0) {
                // TODO Auto-generated method stub
                List<RepairShop> repairShops = Car91JsonUtil.getDTOList(arg0.result.toString(), RepairShop.class);
                if (repairShops.size() > 0) {
                    boolean def = true;
                    List<String> traCalls = new ArrayList<String>();
                    for (RepairShop repairShop : repairShops) {
                        try {
                            if (RegexUtil.isNotNull(repairShop.getDetail().getPhone())) {
                                String[] nums = repairShop.getDetail().getPhone().split("\\s+");
                                traCalls.add(nums[0]);
                                if (def) {
                                    trailView.setText(nums[0]);
                                    def = false;
                                }
                            }
                        } catch (Exception e) {
                        }
                    }
                    if (traCalls.size() > 1) {
                        final String[] strs = new String[traCalls.size()];
                        for (int i = 0; i < strs.length; i++) {
                            strs[i] = traCalls.get(i);
                        }
                        Drawable drawable = getResources().getDrawable(R.drawable.drop);
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        trailView.setCompoundDrawables(null, null, drawable, null);
                        trailView.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View arg0) {
                            	HerilyAlertDialog.Builder builder = new HerilyAlertDialog.Builder(AidActivity.this);
                                builder.setTitle("距您最近拖车商家");
                                builder.setItems(strs, new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface arg0, int arg1) {
										trailView.setText(strs[arg1]);
                                        callPhone(strs[arg1]);
									}
								});
                                builder.create().show();
                            }
                        });
                    } else {
                        trailView.setCompoundDrawables(null, null, null, null);
                        trailView.setOnClickListener(null);
                    }
                } else {
                    trailView.setText(R.string.app_company_customer_phone);
                }
            }
        };

        //救援
        RequestCallBack callHelpBack = new RequestCallBack() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                trafficView.setText(R.string.app_company_customer_phone);
            }

            @Override
            public void onSuccess(ResponseInfo arg0) {
                // TODO Auto-generated method stub
                List<RepairShop> repairShops = Car91JsonUtil.getDTOList(arg0.result.toString(), RepairShop.class);
                if (repairShops.size() > 0) {
                    boolean def = true;
                    List<String> helpCalls = new ArrayList<String>();
                    for (RepairShop repairShop : repairShops) {
                        try {
                            if (RegexUtil.isNotNull(repairShop.getDetail().getPhone())) {
                                String[] nums = repairShop.getDetail().getPhone().split("\\s+");
                                helpCalls.add(nums[0]);
                                if (def) {
                                    trafficView.setText(nums[0]);
                                    def = false;
                                }
                            }
                        } catch (Exception e) {
                        }
                    }
                    if (helpCalls.size() > 1) {
                        final String[] strs = new String[helpCalls.size()];
                        for (int i = 0; i < strs.length; i++) {
                            strs[i] = helpCalls.get(i);
                        }
                        Drawable drawable = getResources().getDrawable(R.drawable.drop);
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        trafficView.setCompoundDrawables(null, null, drawable, null);
                        trafficView.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View arg0) {
                            	HerilyAlertDialog.Builder builder = new HerilyAlertDialog.Builder(AidActivity.this);
                                builder.setTitle("距您最近救援商家");
                                builder.setItems(strs, new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface arg0, int arg1) {
										trafficView.setText(strs[arg1]);
                                        callPhone(strs[arg1]);
									}
								});
                                builder.create().show();
                            }
                        });
                    } else {
                        trafficView.setCompoundDrawables(null, null, null, null);
                        trafficView.setOnClickListener(null);
                    }
                } else {
                    trafficView.setText(R.string.app_company_customer_phone);
                }
            }
        };
    };

    private OnClickListener onPhoneClickListener = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            TableRow tableRow = (TableRow) arg0;
            TextView phoneNumText = (TextView) tableRow.getChildAt(1);
            callPhone(phoneNumText.getText().toString());
        }
    };

    private void callPhone(String phoneNum) {
        String regExpr = "[-_`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regExpr);
        Matcher m = p.matcher(phoneNum);
        phoneNum = m.replaceAll("").trim();
        if (RegexUtil.isDigits(phoneNum)) {
            try {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + phoneNum.trim()));
                startActivity(intent);
            } catch (Exception e) { }
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (locationClient.isStarted()) {
            locationClient.stop();
        }
        try {
            locationClient.unRegisterLocationListener(bdLocationLinstener);
        } catch (Exception e) {
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        if (locationClient.isStarted()) {
            locationClient.stop();
        }
        super.onBackPressed();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        if (locationClient.isStarted()) {
            locationClient.stop();
        }
        super.onStop();
    }
}
